package springcloud.service.impl;


import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import springcloud.dao.OrderDao;
import springcloud.entity.Orders;
import springcloud.service.AccountService;
import springcloud.service.OrderService;
import springcloud.service.StorageService;

import javax.annotation.Resource;

/**
 * @author 韩顺平
 * @version 1.0
 */
@SuppressWarnings("all")
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Resource
    private OrderDao orderDao;

    @Resource
    private StorageService storageService;

    @Resource
    private AccountService accountService;

    @Override
    /**
     * 老师解读
     * 1. @GlobalTransactional : 分布式全局事务控制    io.seata.spring.annotation包
     * 2. name = "yhn-save-order" 名称，程序员自己指定,保证唯一即可
     * 3. rollbackFor = Exception.class 指定发送什么异常就回滚,
     *    这里我们指定的是Exception.class。   即 只要发生了异常就回滚
     */
    @GlobalTransactional(name = "yhn-save-order", rollbackFor = Exception.class)
    public void save(Orders orders) {

        //后面我们如果需要打印日志
        log.info("==== start 创建订单=====");

        log.info("==== start 本地生成订单===");
        //1、调用本地方法生成订单order
        orderDao.save(orders);
        log.info("==== end 本地生成订单===");

        log.info("==== start 扣减库存===");
        //2、远程调用storage微服务模块 扣减库存
        storageService.reduce(orders.getProductId(), orders.getNums());
        log.info("==== end 扣减库存===");

        log.info("==== start 扣减用户余额===");
        //3、远程调用account微服务模块 扣减用户money
        accountService.reduce(orders.getUserId(), orders.getMoney());
        log.info("==== end 扣减用户余额===");

        log.info("==== start 本地修改订单状态===");
        //4、调用本地方法修改订单状态 0 -> 1
        orderDao.update(orders.getUserId(), 0);
        log.info("==== end 本地修改订单状态===");

        log.info("==== end 创建订单=====");
    }
}
